using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace Glpt.Common
{
    /// <summary>
    /// 可查找的组合框控件
    /// </summary>
    public class GJComboBox : ComboBox
    {
        /// <summary>
        /// 初始化类的新实例
        /// </summary>
        public GJComboBox()
            : base()
        {
            base.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        /// <summary>
        /// 引发 System.Windows.Forms.Control.MouseDown 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 System.Windows.Forms.MouseEventArgs。</param>
        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button.Equals(MouseButtons.Right))
            {
                ShowFrom(null);
            }
        }

        private void ShowFrom(KeyPressEventArgs e)
        {
            DataView dv = null;
            if (this.DataSource is DataView)
                dv = (DataView)this.DataSource;
            else if (this.DataSource is DataTable)
                dv = ((DataTable)this.DataSource).DefaultView;
            if (dv != null && dv.Count > 0)
            {
                FrmCombSelectDialog frm = new FrmCombSelectDialog();
                frm.DataBind(dv);
                if (this.SelectedValue != null)
                    frm.SelectedValue = this.SelectedValue;
                frm.ListControl = this;
                if (e != null)
                {
                    frm.KeyCharArgs = e;
                    e.Handled = true;
                }
                frm.Location = this.PointToScreen(new Point(-2, -2));
                frm.Width = this.Width + 20;
                frm.Show();
            }
        }

        /// <summary>
        /// 引发 System.Windows.Forms.Control.KeyPress 事件。
        /// </summary>
        /// <param name="e">包含事件数据的 System.Windows.Forms.KeyPressEventArgs。</param>
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13)
            {
                ShowFrom(e);
            }
            else
                base.OnKeyPress(e);
        }
    }
}
